/**
 * fulihui.com Inc.
 * Copyright (c) 2015-2017 All Rights Reserved.
 */
package com.fulihui.integral.core.strategy.business;

import com.fulihui.integral.core.common.constants.RuleKeys;
import com.fulihui.integral.core.common.entity.RuleData;
import com.fulihui.integral.core.common.utils.ISRuleParseUtil;
import com.fulihui.integral.core.dal.dataobj.ISAccountDetail;
import com.fulihui.integral.core.dal.dataobj.ISAccountDetailExample;
import com.fulihui.integral.core.dal.dataobj.ISRuleInfo;
import com.fulihui.integral.core.dal.dataobj.ISRuleInfoExample;
import com.fulihui.integral.core.dal.mapper.ISAccountDetailMapper;
import com.fulihui.integral.core.dal.mapper.ISRuleInfoMapper;
import com.fulihui.integral.core.enums.ISChannelType;
import com.fulihui.integral.core.enums.ISDoType;
import com.fulihui.integral.core.enums.ISRuleSwitchType;
import com.fulihui.integral.core.strategy.BaseStrategy;
import com.fulihui.integral.core.strategy.StrategyParam;
import com.fulihui.integral.core.strategy.StrategyResult;
import org.near.toolkit.common.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: Levon
 * @version: v 0.1 2017-05-15 10:32
 */
@Component("firstNewsShareStrategy")
public class FirstNewsShareStrategy implements BaseStrategy {

    @Resource
    private ISAccountDetailMapper iSAccountDetailMapper;
    @Resource
    private ISRuleInfoMapper iSRuleInfoMapper;

    /**
     * 根据规则计算积分
     *
     * @param param
     * @return
     */
    @Override
    public StrategyResult calculate(StrategyParam param) {
        StrategyResult result = new StrategyResult();
        String userId = param.getUserId();
        //判断是否首次分享
        List<ISAccountDetail> isAccountDetails = getShareDetail(userId, ISChannelType.FIRST_SHARE.getCode());
        List<ISAccountDetail> shareDetails = getShareDetail(userId, ISChannelType.SHARE.getCode());
        if (CollectionUtils.isEmpty(isAccountDetails) && CollectionUtils.isEmpty(shareDetails)) {
            result.setChannel(ISChannelType.FIRST_SHARE.getCode());
            //查询首次分享规则
            List<ISRuleInfo> isRuleInfos = getShareRules(ISChannelType.FIRST_SHARE.getCode());
            if (CollectionUtils.isEmpty(isRuleInfos)) {
                return result;
            }
            ISRuleInfo isRuleInfo = isRuleInfos.get(0);
            if (StringUtil.equals(ISRuleSwitchType.OFF.getCode(), isRuleInfo.getRuleSwitch())) {
                //首次分享如果关闭，不影响普通分享
                return share(result, userId, shareDetails);
            }
            String ruleTemplate = isRuleInfo.getRuleTemplate();
            if (StringUtil.isNotBlank(ruleTemplate)) {
                Map<String, RuleData> ruleDataMap = ISRuleParseUtil.toMap(ruleTemplate);
                RuleData ruleData = ruleDataMap.get(RuleKeys.FIRST_SHARE);
                if (ruleData != null && StringUtil.isNotBlank(ruleData.getValue())) {
                    result.setAmount(Long.valueOf(ruleData.getValue()));
                }
                return result;
            }
        } else {
            return share(result, userId, shareDetails);
        }
        return result;
    }

    private StrategyResult share(StrategyResult result, String userId, List<ISAccountDetail> shareDetails) {
        result.setChannel(ISChannelType.SHARE.getCode());
        List<ISRuleInfo> isRuleInfos = getShareRules(ISChannelType.SHARE.getCode());
        if (CollectionUtils.isEmpty(isRuleInfos)) {
            return result;
        }
        ISRuleInfo isRuleInfo = isRuleInfos.get(0);
        if (StringUtil.equals(ISRuleSwitchType.OFF.getCode(), isRuleInfo.getRuleSwitch())) {
            return result;
        }
        String ruleTemplate = isRuleInfo.getRuleTemplate();
        if (StringUtil.isNotBlank(ruleTemplate)) {
            Map<String, RuleData> ruleDataMap = ISRuleParseUtil.toMap(ruleTemplate);
            RuleData shareRule = ruleDataMap.get(RuleKeys.SHARE);//文章分享送积分数
            if (shareRule == null || StringUtil.isBlank(shareRule.getValue())) {
                return result;
            }
            RuleData upperLimit = ruleDataMap.get(RuleKeys.UPPER_LIMIT);//鼓励上限次数
            if (upperLimit == null || StringUtil.isBlank(upperLimit.getValue())) {
                return result;
            }
            RuleData intervalTime = ruleDataMap.get(RuleKeys.INTERVAL_TIME);//间隔时间
            if (intervalTime == null || StringUtil.isBlank(intervalTime.getValue())) {
                return result;
            }
            if (!CollectionUtils.isEmpty(shareDetails)) {
                //判断是否达到最大次数
                if (shareDetails.size() >= Long.valueOf(upperLimit.getValue())) {
                    return result;
                }
                //判断间隔时间
                ISAccountDetail isAccountDetail = shareDetails.get(0);
                Date gmtCreate = isAccountDetail.getGmtCreate();
                Long interval = (System.currentTimeMillis() - gmtCreate.getTime()) / (1000 * 60);
                if (interval < Long.valueOf(intervalTime.getValue())) {
                    return result;
                }
            }
            //直接送积分
            result.setAmount(Long.valueOf(shareRule.getValue()));
            return result;
        }
        return result;
    }

    private List<ISAccountDetail> getShareDetail(String userId, String channel) {
        ISAccountDetailExample example = new ISAccountDetailExample();
        ISAccountDetailExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andChannelEqualTo(channel);
        criteria.andOpTypeEqualTo(ISDoType.ADD.getCode());
        example.setOrderByClause("gmt_create desc");
        List<ISAccountDetail> isAccountDetails = iSAccountDetailMapper.selectByExample(example);
        return isAccountDetails;
    }

    private List<ISRuleInfo> getShareRules(String channel) {
        ISRuleInfoExample ruleInfoExample = new ISRuleInfoExample();
        ISRuleInfoExample.Criteria ruleCriteria = ruleInfoExample.createCriteria();
        ruleCriteria.andChannelEqualTo(channel);
        List<ISRuleInfo> isRuleInfos = iSRuleInfoMapper.selectByExample(ruleInfoExample);
        return isRuleInfos;
    }

    @Override
    public ISChannelType getFlag() {
        return ISChannelType.FIRST_SHARE;
    }
}
